import React, { useState, useEffect, useRef, useCallback, type WheelEvent } from 'react';
import './index.scss';
import { DownloadOutlined, RetweetOutlined} from '@ant-design/icons';

interface ImagePreviewProps {
    images: string[]; // 图片URL数组
    visible: boolean; // 是否显示预览
    initialIndex?: number; // 初始图片索引
    onClose: () => void; // 关闭预览回调
}

const ImagePreview: React.FC<ImagePreviewProps> = ({ 
    images, 
    visible, 
    initialIndex = 0,
    onClose 
}) => {
    const [currentIndex, setCurrentIndex] = useState(initialIndex);
    const [rotation, setRotation] = useState(0);
    const [scale, setScale] = useState(1);
    const [position, setPosition] = useState({ x: 0, y: 0 });
    const [isDragging, setIsDragging] = useState(false);
    const [dragStart, setDragStart] = useState({ x: 0, y: 0 });
    const [transition, setTransition] = useState(true);
    const [loadedImages, setLoadedImages] = useState<Record<string, boolean>>({});
    
    const imageRef = useRef<HTMLImageElement>(null);
    const containerRef = useRef<HTMLDivElement>(null);
    const lastTouchRef = useRef<{ distance: number, centerX: number, centerY: number } | null>(null);

    // 重置缩放和旋转状态
    const resetTransform = () => {
        setRotation(0);
        setScale(1);
        setPosition({ x: 0, y: 0 });
    };

    // 切换到上一张图片
    const goToPrev = () => {
        resetTransform();
        setTransition(true);
        setCurrentIndex(prev => (prev > 0 ? prev - 1 : images.length - 1));
    };

    // 切换到下一张图片
    const goToNext = () => {
        resetTransform();
        setTransition(true);
        setCurrentIndex(prev => (prev < images.length - 1 ? prev + 1 : 0));
    };

    // 处理键盘事件
    const handleKeyDown = useCallback((e: KeyboardEvent) => {
        if (!visible) return;
        
        switch (e.key) {
            case 'Escape':
                onClose();
                break;
            case 'ArrowLeft':
                goToPrev();
                break;
            case 'ArrowRight':
                goToNext();
                break;
            default:
                break;
        }
    }, [visible, onClose, goToPrev, goToNext]);

    // 处理鼠标滚轮缩放
    const handleWheel = useCallback((e: WheelEvent) => {
        if (!visible || !containerRef.current || !imageRef.current) return;
        
        e.preventDefault();
        const delta = e.deltaY;
        
        // 计算图像中心点在容器中的位置
        const rect = imageRef.current.getBoundingClientRect();
        const containerRect = containerRef.current.getBoundingClientRect();
        
        const centerX = (rect.left + rect.width/2 - containerRect.left);
        const centerY = (rect.top + rect.height/2 - containerRect.top);
        
        // 计算新的缩放比例
        let newScale: number;
        if (delta < 0) {
        newScale = Math.min(scale * 1.2, 5);
        } else {
        newScale = Math.max(scale * 0.8, 0.2);
        }
        
        // 计算缩放后的偏移位置
        const originX = (e.clientX - containerRect.left - centerX);
        const originY = (e.clientY - containerRect.top - centerY);
        
        setPosition(prev => ({
        x: prev.x - (originX / scale) * (newScale - scale),
        y: prev.y - (originY / scale) * (newScale - scale)
        }));
        
        setScale(newScale);
        setTransition(false);
    }, [visible, scale]);

    // 处理图片加载
    const handleImageLoad = (url: string) => {
        setLoadedImages(prev => ({ ...prev, [url]: true }));
    };

    // 切换到指定索引的图片
    const goToImage = (index: number) => {
        setTransition(true);
        setCurrentIndex(index);
        resetTransform();
    };

    // 旋转图片
    const rotateImage = (angle: number) => {
        setRotation(prev => (prev + angle) % 360);
    };

    // 缩放图片
    const zoomImage = (factor: number) => {
        if (!imageRef.current || !containerRef.current) return;
        
        // 计算缩放中心（容器中心）
        const rect = containerRef.current.getBoundingClientRect();
        const containerCenterX = rect.width / 2;
        const containerCenterY = rect.height / 2;
        
        // 计算当前图像中心位置（相对于容器）
        const imgRect = imageRef.current.getBoundingClientRect();
        const imgCenterX = imgRect.left - rect.left + imgRect.width / 2;
        const imgCenterY = imgRect.top - rect.top + imgRect.height / 2;
        
        // 计算新的缩放比例
        const newScale = Math.max(Math.min(scale * factor, 5), 0.2);
        
        // 计算偏移量以保持缩放中心
        const scaleChange = newScale - scale;
        
        setPosition(prev => ({
        x: prev.x - (containerCenterX - imgCenterX) * (scaleChange / scale),
        y: prev.y - (containerCenterY - imgCenterY) * (scaleChange / scale)
        }));
        
        setScale(newScale);
        setTransition(false);
    };

    // 下载图片
    const downloadImage = () => {
        fetch(images[currentIndex])
            .then(response => response.blob())
            .then(blob => {
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = images[currentIndex];
            a.download = `image-${Date.now()}`;
            document.body.appendChild(a);
            a.click();
            window.URL.revokeObjectURL(url);
            document.body.removeChild(a);
        })
        .catch(error => console.error('下载失败:', error));
    };

    // 处理鼠标按下事件（开始拖动）
    const handleMouseDown = (e: React.MouseEvent) => {
        if (scale === 1) return;
        
        e.preventDefault();
        setIsDragging(true);
        setDragStart({ x: e.clientX, y: e.clientY });
        setTransition(false);
    };

    // 处理鼠标移动事件（拖动中）
    const handleMouseMove = (e: MouseEvent) => {
        if (!isDragging) return;
        
        e.preventDefault();
        setPosition(prev => ({
        x: prev.x + (e.clientX - dragStart.x),
        y: prev.y + (e.clientY - dragStart.y)
        }));
        setDragStart({ x: e.clientX, y: e.clientY });
    };

    // 处理鼠标松开事件（结束拖动）
    const handleMouseUp = () => {
        setIsDragging(false);
    };

    // 处理触摸开始事件
    const handleTouchStart = (e: React.TouchEvent) => {
        if (e.touches.length === 1) {
            // 单指操作 - 拖动
            const touch = e.touches[0];
            setIsDragging(true);
            setDragStart({ x: touch.clientX, y: touch.clientY });
            setTransition(false);
        } else if (e.touches.length === 2) {
            // 双指操作 - 缩放
            const touch1 = e.touches[0];
            const touch2 = e.touches[1];
            
            const distance = Math.sqrt(
                Math.pow(touch1.clientX - touch2.clientX, 2) +
                Math.pow(touch1.clientY - touch2.clientY, 2)
            );
            
            const centerX = (touch1.clientX + touch2.clientX) / 2;
            const centerY = (touch1.clientY + touch2.clientY) / 2;
            
            lastTouchRef.current = {
                distance,
                centerX,
                centerY
            };
        }
    };

    // 处理触摸移动事件
    const handleTouchMove = (e: TouchEvent) => {
        e.preventDefault();
        
        if (e.touches.length === 1 && isDragging) {
            // 单指拖动
            const touch = e.touches[0];
            setPosition(prev => ({
                x: prev.x + (touch.clientX - dragStart.x),
                y: prev.y + (touch.clientY - dragStart.y)
            }));
            setDragStart({ x: touch.clientX, y: touch.clientY });
        } else if (e.touches.length === 2 && containerRef.current) {
            // 双指缩放
            const touch1 = e.touches[0];
            const touch2 = e.touches[1];
            
            const distance = Math.sqrt(
                Math.pow(touch1.clientX - touch2.clientX, 2) +
                Math.pow(touch1.clientY - touch2.clientY, 2)
            );
            
            const centerX = (touch1.clientX + touch2.clientX) / 2;
            const centerY = (touch1.clientY + touch2.clientY) / 2;
            
            const rect = containerRef.current.getBoundingClientRect();
            const imgRect = imageRef.current?.getBoundingClientRect();
            
            if (!lastTouchRef.current || !imgRect) return;
            
            // 计算新缩放比例
            const scaleChange = distance / lastTouchRef.current.distance;
            const newScale = Math.max(Math.min(scale * scaleChange, 5), 0.2);
            
            if (newScale !== scale) {
                // 计算图像中心位置（相对于容器）
                const containerCenterX = centerX - rect.left;
                const containerCenterY = centerY - rect.top;
                
                // 计算当前图像位置（相对于容器）
                const imgCenterX = (imgRect.left - rect.left) + imgRect.width / 2;
                const imgCenterY = (imgRect.top - rect.top) + imgRect.height / 2;
                
                // 计算偏移量以保持缩放中心
                const scaleChange = newScale - scale;
                
                setPosition(prev => ({
                x: prev.x - (containerCenterX - imgCenterX) * (scaleChange / scale),
                y: prev.y - (containerCenterY - imgCenterY) * (scaleChange / scale)
                }));
                
                setScale(newScale);
            }
            
            lastTouchRef.current = { distance, centerX, centerY };
        }
    };

    // 处理触摸结束事件
    const handleTouchEnd = () => {
        setIsDragging(false);
        lastTouchRef.current = null;
    };

    // 点击背景关闭预览
    const handleBackdropClick = (e: React.MouseEvent) => {
        if ((e.target as Element).className?.includes?.('image-preview-backdrop')) {
        onClose();
        }
    };

    // 初始化事件监听
    useEffect(() => {
        if (visible) {
        // 初始化索引状态
        setCurrentIndex(initialIndex);
        resetTransform();
        setTransition(true);
        
        // 记录滚动位置以便在预览后恢复
        const scrollY = window.scrollY;
        document.body.style.overflow = 'hidden';
        document.body.style.position = 'fixed';
        document.body.style.top = `-${scrollY}px`;
        document.body.style.width = '100%';
        
        return () => {
            // 恢复滚动
            document.body.style.overflow = '';
            document.body.style.position = '';
            document.body.style.top = '';
            window.scrollTo(0, scrollY);
        };
        }
    }, [visible]);

    // 添加键盘事件监听
    useEffect(() => {
        window.addEventListener('keydown', handleKeyDown);
        return () => {
        window.removeEventListener('keydown', handleKeyDown);
        };
    }, [handleKeyDown]);

    // 添加鼠标移动事件监听
    useEffect(() => {
        window.addEventListener('mousemove', handleMouseMove);
        window.addEventListener('mouseup', handleMouseUp);
        window.addEventListener('touchmove', handleTouchMove as any);
        window.addEventListener('touchend', handleTouchEnd);
        
        return () => {
        window.removeEventListener('mousemove', handleMouseMove);
        window.removeEventListener('mouseup', handleMouseUp);
        window.removeEventListener('touchmove', handleTouchMove as any);
        window.removeEventListener('touchend', handleTouchEnd);
        };
    }, [handleMouseMove]);

    // 重置滚动位置
    useEffect(() => {
        if (!visible) return;
        
        const scrollY = window.scrollY;
        document.body.style.position = 'fixed';
        document.body.style.top = `-${scrollY}px`;
        
        return () => {
        document.body.style.position = '';
        window.scrollTo(0, scrollY);
        };
    }, [visible]);

    if (!visible) return null;

    return (
        <div 
            className="image-preview-backdrop"
            onMouseDown={handleBackdropClick}
        >
            <div className="image-preview-container" ref={containerRef}>
                {/* 上一张按钮 */}
                <button 
                    title='上一张'
                    className={`nav-button prev ${images.length <= 1 ? 'disabled' : ''}`}
                    onClick={goToPrev}
                    disabled={images.length <= 1}
                >
                    <i className="icon icon-left"></i>
                </button>
                
                {/* 主图展示区 */}
                <div className="image-viewport" onWheel={handleWheel}>
                    {images.map((src, index) => (
                        <div 
                            key={src}
                            className={`slide ${index === currentIndex ? 'active' : ''}`}
                            style={{ 
                                transform: `translateX(${(index - currentIndex) * 100}%)`,
                                transition: transition ? 'transform 0.3s ease' : 'none'
                            }}
                        >
                            <div 
                                className="image-container"
                                style={{ 
                                transform: index === currentIndex ? 
                                    `scale(${scale}) translate(${position.x}px, ${position.y}px) rotate(${rotation}deg)` : '',
                                transition: transition ? 'transform 0.3s ease' : 'none'
                                }}
                                onMouseDown={e => index === currentIndex && handleMouseDown(e)}
                                onTouchStart={e => index === currentIndex && handleTouchStart(e)}
                            >
                                <img
                                    ref={index === currentIndex ? imageRef : null}
                                    src={src}
                                    alt={`Preview ${index + 1}`}
                                    onLoad={() => handleImageLoad(src)}
                                    loading='lazy'
                                    style={{ opacity: loadedImages[src] ? 1 : 0 }}
                                />
                                    {!loadedImages[src] && (
                                    <div className="image-loader">
                                        <div className="spinner"></div>
                                        <span>加载中...</span>
                                    </div>
                                )}
                            </div>
                        </div>
                    ))}
                </div>
                
                {/* 下一张按钮 */}
                <button 
                    title='下一张'
                    className={`nav-button next ${images.length <= 1 ? 'disabled' : ''}`}
                    onClick={goToNext}
                    disabled={images.length <= 1}
                >
                    <i className="icon icon-right"></i>
                </button>
                
                {/* 操作工具栏 */}
                <div className="toolbar">
                    <button 
                        className="toolbar-button"
                        onClick={() => rotateImage(-90)}
                        title="向左旋转"
                    >
                        <i className="icon">
                            <svg viewBox="64 64 896 896" focusable="false" data-icon="rotate-left" width="1em" height="1em" fill="currentColor" aria-hidden="true"><defs><style></style></defs><path d="M672 418H144c-17.7 0-32 14.3-32 32v414c0 17.7 14.3 32 32 32h528c17.7 0 32-14.3 32-32V450c0-17.7-14.3-32-32-32zm-44 402H188V494h440v326z"></path><path d="M819.3 328.5c-78.8-100.7-196-153.6-314.6-154.2l-.2-64c0-6.5-7.6-10.1-12.6-6.1l-128 101c-4 3.1-3.9 9.1 0 12.3L492 318.6c5.1 4 12.7.4 12.6-6.1v-63.9c12.9.1 25.9.9 38.8 2.5 42.1 5.2 82.1 18.2 119 38.7 38.1 21.2 71.2 49.7 98.4 84.3 27.1 34.7 46.7 73.7 58.1 115.8a325.95 325.95 0 016.5 140.9h74.9c14.8-103.6-11.3-213-81-302.3z"></path>
                            </svg>
                        </i>
                    </button>
                    
                    <button 
                        className="toolbar-button"
                        onClick={() => rotateImage(90)}
                        title="向右旋转"
                    >
                        <i className="icon">
                            <svg viewBox="64 64 896 896" focusable="false" data-icon="rotate-right" width="1em" height="1em" fill="currentColor" aria-hidden="true"><defs><style></style></defs><path d="M480.5 251.2c13-1.6 25.9-2.4 38.8-2.5v63.9c0 6.5 7.5 10.1 12.6 6.1L660 217.6c4-3.2 4-9.2 0-12.3l-128-101c-5.1-4-12.6-.4-12.6 6.1l-.2 64c-118.6.5-235.8 53.4-314.6 154.2A399.75 399.75 0 00123.5 631h74.9c-.9-5.3-1.7-10.7-2.4-16.1-5.1-42.1-2.1-84.1 8.9-124.8 11.4-42.2 31-81.1 58.1-115.8 27.2-34.7 60.3-63.2 98.4-84.3 37-20.6 76.9-33.6 119.1-38.8z"></path><path d="M880 418H352c-17.7 0-32 14.3-32 32v414c0 17.7 14.3 32 32 32h528c17.7 0 32-14.3 32-32V450c0-17.7-14.3-32-32-32zm-44 402H396V494h440v326z"></path></svg>
                        </i>
                    </button>
                    
                    <button 
                        className="toolbar-button"
                        onClick={() => zoomImage(1.2)}
                        title="放大"
                    >
                        <i className="icon">
                            <svg viewBox="64 64 896 896" focusable="false" data-icon="zoom-in" width="1em" height="1em" fill="currentColor" aria-hidden="true"><path d="M637 443H519V309c0-4.4-3.6-8-8-8h-60c-4.4 0-8 3.6-8 8v134H325c-4.4 0-8 3.6-8 8v60c0 4.4 3.6 8 8 8h118v134c0 4.4 3.6 8 8 8h60c4.4 0 8-3.6 8-8V519h118c4.4 0 8-3.6 8-8v-60c0-4.4-3.6-8-8-8zm284 424L775 721c122.1-148.9 113.6-369.5-26-509-148-148.1-388.4-148.1-537 0-148.1 148.6-148.1 389 0 537 139.5 139.6 360.1 148.1 509 26l146 146c3.2 2.8 8.3 2.8 11 0l43-43c2.8-2.7 2.8-7.8 0-11zM696 696c-118.8 118.7-311.2 118.7-430 0-118.7-118.8-118.7-311.2 0-430 118.8-118.7 311.2-118.7 430 0 118.7 118.8 118.7 311.2 0 430z"></path></svg>
                        </i>
                    </button>
                    
                    <button 
                        className="toolbar-button"
                        onClick={() => zoomImage(0.8)}
                        title="缩小"
                    >
                        <i className="icon">
                            <svg viewBox="64 64 896 896" focusable="false" data-icon="zoom-out" width="1em" height="1em" fill="currentColor" aria-hidden="true"><path d="M637 443H325c-4.4 0-8 3.6-8 8v60c0 4.4 3.6 8 8 8h312c4.4 0 8-3.6 8-8v-60c0-4.4-3.6-8-8-8zm284 424L775 721c122.1-148.9 113.6-369.5-26-509-148-148.1-388.4-148.1-537 0-148.1 148.6-148.1 389 0 537 139.5 139.6 360.1 148.1 509 26l146 146c3.2 2.8 8.3 2.8 11 0l43-43c2.8-2.7 2.8-7.8 0-11zM696 696c-118.8 118.7-311.2 118.7-430 0-118.7-118.8-118.7-311.2 0-430 118.8-118.7 311.2-118.7 430 0 118.7 118.8 118.7 311.2 0 430z"></path></svg>
                        </i>
                    </button>
                    
                    <button 
                        className="toolbar-button"
                        onClick={resetTransform}
                        title="重置"
                    >
                        <i className="icon">
                            <RetweetOutlined />
                        </i>
                    </button>
                    
                    <button 
                        className="toolbar-button"
                        onClick={downloadImage}
                        title="下载"
                    >
                        <i className="icon">
                            <DownloadOutlined></DownloadOutlined>
                        </i>
                    </button>
                    
                    <button 
                        className="toolbar-button close-button"
                        onClick={onClose}
                        title="关闭预览"
                    >
                        <i className="icon">
                            <svg fill-rule="evenodd" viewBox="64 64 896 896" focusable="false" data-icon="close" width="1em" height="1em" fill="currentColor" aria-hidden="true"><path d="M799.86 166.31c.02 0 .04.02.08.06l57.69 57.7c.04.03.05.05.06.08a.12.12 0 010 .06c0 .03-.02.05-.06.09L569.93 512l287.7 287.7c.04.04.05.06.06.09a.12.12 0 010 .07c0 .02-.02.04-.06.08l-57.7 57.69c-.03.04-.05.05-.07.06a.12.12 0 01-.07 0c-.03 0-.05-.02-.09-.06L512 569.93l-287.7 287.7c-.04.04-.06.05-.09.06a.12.12 0 01-.07 0c-.02 0-.04-.02-.08-.06l-57.69-57.7c-.04-.03-.05-.05-.06-.07a.12.12 0 010-.07c0-.03.02-.05.06-.09L454.07 512l-287.7-287.7c-.04-.04-.05-.06-.06-.09a.12.12 0 010-.07c0-.02.02-.04.06-.08l57.7-57.69c.03-.04.05-.05.07-.06a.12.12 0 01.07 0c.03 0 .05.02.09.06L512 454.07l287.7-287.7c.04-.04.06-.05.09-.06a.12.12 0 01.07 0z"></path></svg>
                        </i>
                    </button>
                </div>
                
                {/* 图片索引指示器 */}
                <div className="image-indicator">
                    {currentIndex + 1} / {images.length}
                </div>
                
                {/* 缩略图导航 */}
                {images.length > 1 && (
                <div className="thumbnail-nav">
                    {images.map((src, index) => (
                    <div 
                        key={src}
                        className={`thumbnail ${index === currentIndex ? 'active' : ''}`}
                        onClick={() => goToImage(index)}
                    >
                        <img src={src} alt={`Thumbnail ${index + 1}`} />
                        {index === currentIndex && <div className="active-border"></div>}
                    </div>
                    ))}
                </div>
                )}
            </div>
        </div>
    );
};

export default ImagePreview;